// modbus_tool.h
#ifndef MODBUS_TOOL_H
#define MODBUS_TOOL_H

#include "modbus_base.h"
#include "serial_interface.h"
#include "modbus_interface.h"


class ModbusTool : public ModbusBase , public ModbusInterface{
public:
    ModbusTool();
    ~ModbusTool();

    bool start(const std::string& port, int baud_rate = 115200) override;
    void stop();

    void query_registers(uint8_t machine_addr, uint16_t start_addr, uint16_t end_addr) override;
    void write_single_register(uint8_t machine_addr, uint16_t addr, uint16_t value) override;
    void write_multiple_registers(uint8_t machine_addr, uint16_t start_addr, const std::vector<uint16_t>& values) override;
    // 接收消息监听函数
    void query_onmsg(const OnMsgCallback &cb) override { query_cb_ = cb; }
    void single_onmsg(const OnMsgCallback &cb) override { single_cb_ = cb; }
    void multiple_onmsg(const OnMsgCallback &cb) override { multiple_cb_ = cb;}
    OnMsgCallback query_cb_;
    OnMsgCallback single_cb_;
    OnMsgCallback multiple_cb_;
    std::atomic<bool> running_{false};
    
private:
    /**
     * @brief 打印十六进制格式的数据
     * @param prefix 前缀标识 (如 "RX" 或 "TX")
     * @param data 数据指针
     * @param length 数据长度
     */
    void print_hex_data(const std::string& prefix, const uint8_t* data, size_t length) {
        std::ostringstream oss;
        oss << "[" << prefix << "] ";
        
        // 设置输出格式为十六进制，两位数，前导零
        oss << std::hex << std::setfill('0');
        
        for (size_t i = 0; i < length; ++i) {
            oss << std::setw(2) << static_cast<int>(data[i]) << " ";
        }
        
        // 添加字节数信息
        oss << "(" << std::dec << length << " bytes)";
        
        std::cout << oss.str() << std::endl;
    }
    void receive_thread_func();

    void parse_response(const uint8_t* buffer, size_t length);

    std::unique_ptr<SerialInterface> serial_;
    std::thread receive_thread_;
};

#endif // MODBUS_TOOL_H
